var Login = function () {
// 显示错误函数
    function showError(info, target) {
        $('.alert-danger', $(target)).show();
        $('.alert-danger', $(target)).find("span").html(info);
    }

    var util = {
        serializeObject: function (form) {
            var formEL = form;
            var o = {};
            var a = formEL.serializeArray();
            $.each(a, function () {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        },

        fillFormData: function (form, obj, isStatus) {
            var formEL = $(form);
            $.each(obj, function (index, item) {
                formEL.find("[name=" + index + "]").val(item);
            });
        },
        empty: function (data) {
            if (null == data || "" == data) return true;
            else return false;
        }
    };
    /*登录*/
    var handleLogin = function (path) {
        /*登录校验*/
        $('#login-form').validate({
            // debug: true,
            errorElement: 'span',
            errorClass: 'help-block',
            focusInvalid: false,
            rules: {
                userName: {
                    required: true
                },
                password: {
                    required: true
                },
                captcha: {
                    required: true,
                    remote: {
                        url: path + '/sysLogin/captcha',
                        type: "post",               //数据发送方式
                        data: {
                            "captcha": function () {
                                var value = $("input[name='captcha']").val();
                                return $("input[name='captcha']").val();
                            }
                        }
                    }
                }
            },
            messages: {
                userName: {
                    required: "用户名不能为空"
                },
                password: {
                    required: "密码不能为空"
                },
                captcha: {
                    required: "验证码不能为空",
                    remote: "验证码不正确"
                }
            },
            // 如果表单有没有通过验证的元素，就会触发invalid-form事件，如果invalidHandler事件处理函数存在，那么就会执行此函数
            invalidHandler: function (event, validator) {
                showError(validator.errorList[0].message, "#login-form");
            },
            // element出错时触发
            // highlight: function (element) {
            highlight: function (element) {
                // debugger;
                $(element).closest('.form-group').addClass('has-error');
            },

            success: function (label) {
                label.closest('.form-group').removeClass('has-error');
                label.remove();
            },
            // 插入错误信息
            errorPlacement: function (error, element) {
                error.insertAfter(element.closest('.form-control'));
            },
            submitHandler: function (form) {
                var json = util.serializeObject($('#login-form'));
                json = JSON.stringify(json);
                $.ajax({
                    url: path + "/sysLogin/login",
                    data: json,
                    type: "post",
                    async: false,
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (result) {
                        if ("success" == result.type) {
                            // alert("jzy"+path)
                            layer.msg(result.info, {icon: 1, time: 1500});
                                window.location.href = "index.jsp";
                            // window.location.href = "index.jsp";
                        } else if ("error" == result.type) {
                            layer.msg(result.info, {icon: 2, time: 1500});
                        }
                    },
                    error: function (msg) {
                        showError("登录失败", "#login-form");

                    }
                });
            }
        });

        /*按确认键登录*/
        $('#login-form input').keypress(function (e) {
            //enter键按下
            if (e.which == 13) {
                if ($('#login-form').validate().form()) {
                    $('#login-form').submit(); //form validation success, call ajax form submit
                }
                return false;
            }
        });
        /*忘记密码form表单*/
        $('.forget-form input').keypress(function (e) {
            //enter键按下，form表单校验，并提交
            if (e.which == 13) {
                if ($('.forget-form').validate().form()) {
                    $('.forget-form').submit();
                }
                return false;
            }
        });
        /*忘记密码表单按钮*/
        $('#forget-password').click(function () {
            $('#login-form').hide();
            $('.register-form').hide();
            $('.forget-form').show();
        });
        /*忘记密码返回表单按钮*/
        $('#back-btn').click(function () {
            $('#login-form').show();
            $('.register-form').hide();
            $('.forget-form').hide();
        });
        /*忘记密码返回表单按钮*/
        $('#back-btn').click(function () {
            $('#login-form').show();
            $('.register-form').hide();
            $('.forget-form').hide();
        });
        /*注册返回表单按钮*/
        $('#register-back-btn').click(function () {
            $('#login-form').show();
            $('.register-form').hide();
            $('.forget-form').hide();
        });

        /*显示注册页面*/
        $('#register-btn').click(function () {
            $('#login-form').hide();
            $('.register-form').show();
            $('.forget-form').hide();
        });


    };
    /*忘记密码*/
    var handleForgetPassword = function (path) {
        $('#forget-form').validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-block', // default input error message class
            focusInvalid: false, // do not focus the last invalid input
            ignore: "",
            rules: {
                email: {
                    required: true,
                    email: true
                }
            },

            messages: {
                email: {
                    required: "邮箱不能为空"
                }
            },

            invalidHandler: function (event, validator) { //display error alert on form submit
                showError(validator.errorList[0].message, "#forget-form");
            },

            highlight: function (element) { // hightlight error inputs
                // debugger;
                $(element).closest('.form-group').addClass('has-error'); // set error class to the control group
            },

            success: function (label) {
                label.closest('.form-group').removeClass('has-error');
                label.remove();
            },

            errorPlacement: function (error, element) {
                // form-control
                // error.insertAfter(element.closest('.input-icon'));
                error.insertAfter(element.closest('.form-control'));
            },

            submitHandler: function (form) {
                form.submit();
            }
        });

        $('.forget-form input').keypress(function (e) {
            if (e.which == 13) {
                if ($('.forget-form').validate().form()) {
                    $('.forget-form').submit();
                }
                return false;
            }
        });

        jQuery('#forget-password').click(function () {
            jQuery('#login-form').hide();
            jQuery('.forget-form').show();
        });

        jQuery('#back-btn').click(function () {
            jQuery('#login-form').show();
            jQuery('.forget-form').hide();
        });

    };
    /*注册*/

    var handleRegister = function (path) {
        $('#registerForm').validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-block', // default input error message class
            focusInvalid: false, // do not focus the last invalid input
            ignore: "",
            rules: {
                userName: {
                    required: true,
                    remote: {
                        url: path + '/authority/login/Selname',//校验用户名是否存在，并唯一
                        type: "post",//数据发送方式
                        data: {
                            "userName": function () {
                                var value = $("#registerForm  input[name='userName']").val();
                                return value;
                            }
                        }
                    }
                },
                userEmail: {
                    required: true,
                    email: true,
                    remote: {//远程校验邮箱是否存在
                        url: path + '/authority/login/Selemail',
                        type: "post",               //数据发送方式
                        data: {
                            "captcha": function () {
                                var value = $("#registerForm  input[name='userEmail']").val();
                                return value;
                            }
                        }
                    }
                },
                password: {
                    required: true,
                    minlength: 6,
                    maxlength: 8
                },
                rpassword: {
                    equalTo: "#registerForm #password"
                }
            },

            messages: {
                userName: {
                    required: "用户名不能为空",
                    remote: "用户名已经存在"
                },
                userEmail: {
                    required: "邮箱不能为空",
                    email: "邮箱" +
                        "格式不正确",
                    remote: "邮箱已经存在"
                },
                password: {
                    required: "密码不能为空",
                    minlength: "密码长度不符",
                    maxlength: "密码长度不符"
                },
                rpassword: {
                    equalTo: "确认密码不匹配"
                }
            },


            invalidHandler: function (event, validator) { //display error alert on form submit
                showError(validator.errorList[0].message, "#registerForm");
            },

            highlight: function (element) { // hightlight error inputs
                $(element).closest('.form-group').addClass('has-error'); // set error class to the control group
            },
            // mustChecked
            success: function (label) {
                label.closest('.form-group').removeClass('has-error');
                // label.closest('.mustChecked').removeClass('has-error');
                label.remove();
            },

            errorPlacement: function (error, element) {
                error.insertAfter(element.closest('.form-control'));
            },

            submitHandler: function (form) {
                // debugger;
                var json = util.serializeObject($('#registerForm'));
                json = JSON.stringify(json);
                // debugger;
                $.ajax({
                    url: path + "/authority/login/register",
                    data: json,
                    type: "post",
                    async: false,
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        // debugger;
                        if ("success" == result.type) {
                            layer.msg(result.info, {icon: 1, time: 1500});
                            window.location.href = "login.jsp"
                        } else if ("error" == result.type) {
                            layer.msg(result.info, {icon: 2, time: 1500});
                            $('#form')[0].reset();

                        }
                        // layer.msg("注册成功");
                    },
                    error: function (msg) {
                        layer.msg("注册失败");

                    }
                });


            }
        });

        $('#registerForm input').keypress(function (e) {
            if (e.which == 13) {
                if ($('.register-form').validate().form()) {
                    $('.register-form').submit();
                }
                return false;
            }
        });

        jQuery('#register-btn').click(function () {
            jQuery('#login-form').hide();
            jQuery('.register-form').show();
        });

        jQuery('#register-back-btn').click(function () {
            jQuery('#login-form').show();
            jQuery('.register-form').hide();
        });
    };

    return {
        //main function to initiate the module
        init: function (path) {

            handleLogin(path);
            handleForgetPassword(path);
            handleRegister(path);
        }

    };


}();

